#ifndef GDALCPP_HPP
#define GDALCPP_HPP

/*

C++11 wrapper classes for GDAL/OGR.

Version 1.3.0

https://github.com/joto/gdalcpp

Copyright 2015-2021 Jochen Topf <jochen@topf.org>

Boost Software License - Version 1.0 - August 17th, 2003

Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:

The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

*/

#include <gdal_priv.h>
#include <gdal_version.h>
#include <ogr_api.h>
#include <ogrsf_frmts.h>

#include "GISDef.h"

namespace OCPP {

    using gdal_driver_type = GDALDriver;
    using gdal_dataset_type = GDALDataset;


    /**
     * Exception thrown for all errors in this class.
     */
    class _GISExport gdal_error : public std::runtime_error {

        String m_driver;
        String m_dataset;
        String m_layer;
        String m_field;
        OGRErr m_error;

    public:

        gdal_error(const String& message,
            OGRErr error,
            const String& driver = "",
            const String& dataset = "",
            const String& layer = "",
            const String& field = "");

        const String& driver() const noexcept {
            return m_driver;
        }

        const String& dataset() const noexcept {
            return m_dataset;
        }

        const String& layer() const noexcept {
            return m_layer;
        }

        const String& field() const noexcept {
            return m_field;
        }

        OGRErr error() const noexcept {
            return m_error;
        }

    }; // class gdal_error

    namespace detail {

        struct init_wrapper {

            init_wrapper() noexcept;
        }; // struct init_wrapper

        struct init_library {

            init_library() {
                static init_wrapper iw;
            }

        }; // struct init_library

        class _GISExport Driver : private init_library {

            gdal_driver_type* m_driver;

        public:

            Driver(const String& driver_name);

            gdal_driver_type& get() const noexcept {
                return *m_driver;
            }

        }; // struct Driver

        struct Options {

            std::vector<String> m_options;
            std::unique_ptr<const char*[]> m_ptrs;

            Options(const std::vector<String>& options) :
                m_options(options),
                m_ptrs(new const char*[options.size() + 1]) {
                std::transform(m_options.begin(), m_options.end(), m_ptrs.get(), [&](const String& s) {
                    return s.data();
                });
                m_ptrs[options.size()] = nullptr;
            }

            char** get() const noexcept {
                return const_cast<char**>(m_ptrs.get());
            }

        }; // struct Options

    } // namespace detail
    struct ogr_transform_deleter {
        void operator()(OGRCoordinateTransformation* ct) {
            OGRCoordinateTransformation::DestroyCT(ct);
        }

    }; // struct ogr_geometry_deleter

    using transform_type = std::unique_ptr<OGRCoordinateTransformation, ogr_transform_deleter>;

    class _GISExport SRS {

        OGRSpatialReference m_spatial_reference;
        OGRSpatialReference m_spatial_referenceTo;
        transform_type      m_transform_type;
    public:

        SRS() :
            m_spatial_reference() {
            const auto result = m_spatial_reference.SetWellKnownGeogCS("CRS84");
            if (result != OGRERR_NONE) {
                throw gdal_error{String{"can not initialize spatial reference system WGS84"},
                                 result};
            }
        }

        explicit SRS(int epsg) :
            m_spatial_reference() {
            const auto result = m_spatial_reference.importFromEPSG(epsg);
            if (result != OGRERR_NONE) {
                throw gdal_error{String{"can not initialize spatial reference system for EPSG:"} + std::to_string(epsg),
                                 result};
            }
        }

        explicit SRS(const char* name) :
            m_spatial_reference() {
            const auto result = m_spatial_reference.importFromProj4(name);
            if (result != OGRERR_NONE) {
                throw gdal_error{String{"can not initialize spatial reference system '"} + name + "'",
                                 result};
            }
        }

        explicit SRS(const String& name) :
            m_spatial_reference() {
            const auto result = m_spatial_reference.importFromProj4(name.c_str());
            if (result != OGRERR_NONE) {
                throw gdal_error{String{"can not initialize spatial reference system '"} + name + "'",
                                 result};
            }
        }

        explicit SRS(const SRS& srs_reference) :
            m_spatial_reference(srs_reference.m_spatial_reference),
            m_spatial_referenceTo(srs_reference.m_spatial_referenceTo),
            m_transform_type()
        {

        }
        explicit SRS(const OGRSpatialReference& spatial_reference, const OGRSpatialReference& spatial_referenceTo) :
            m_spatial_reference(spatial_reference),
            m_spatial_referenceTo(spatial_referenceTo),
            m_transform_type()
        {
        }

        OGRSpatialReference& get() noexcept {
            return m_spatial_reference;
        }

        const OGRSpatialReference& get() const noexcept {
            return m_spatial_reference;
        }

        OGRCoordinateTransformation* getTransform(int epsg) {
            if (m_transform_type == nullptr) {
                m_spatial_referenceTo.importFromEPSG(epsg);
                m_transform_type.reset(OGRCreateCoordinateTransformation(&m_spatial_reference, &m_spatial_referenceTo));
            }
            return m_transform_type.get(); 
        }

        OGRCoordinateTransformation* getTransform(const String& name) {
            if (m_transform_type == nullptr) {
                m_spatial_referenceTo.importFromProj4(name.c_str());
                m_transform_type.reset(OGRCreateCoordinateTransformation(&m_spatial_reference, &m_spatial_referenceTo));
            }
            return m_transform_type.get();
        }
    }; // class SRS

    class _GISExport Dataset {

        struct gdal_dataset_deleter {

            void operator()(gdal_dataset_type* ds);

        }; // struct gdal_dataset_deleter

        String m_driver_name;
        String m_dataset_name;
        detail::Options m_options;
        SRS m_srs;
        std::unique_ptr<gdal_dataset_type, gdal_dataset_deleter> m_dataset;
        uint64_t m_edit_count = 0;
        uint64_t m_max_edit_count = 0;

    public:

        Dataset(const String& driver_name, const String& dataset_name, const SRS& srs = SRS{}, const std::vector<String>& options = {}) :
            m_driver_name(driver_name),
            m_dataset_name(dataset_name),
            m_options(options),
            m_srs(srs),
            m_dataset(detail::Driver(driver_name).get().Create(dataset_name.c_str(), 0, 0, 0, GDT_Unknown, m_options.get())) {
            if (!m_dataset) {
                throw gdal_error{String{"failed to create dataset '"} + dataset_name + "'",
                                 OGRERR_NONE,
                                 driver_name,
                                 dataset_name};
            }
        }

        ~Dataset() noexcept {
            try {
                if (m_edit_count > 0) {
                    commit_transaction();
                }
            } catch (...) {
            }
        }

        const String& driver_name() const noexcept {
            return m_driver_name;
        }

        const String& dataset_name() const noexcept {
            return m_dataset_name;
        }

        gdal_dataset_type& get() const noexcept {
            return *m_dataset;
        }

        SRS& srs() noexcept {
            return m_srs;
        }

        void exec(const char* sql) {
            const auto result = m_dataset->ExecuteSQL(sql, nullptr, nullptr);
            if (result) {
                m_dataset->ReleaseResultSet(result);
            }
        }

        void exec(const String& sql) {
            exec(sql.c_str());
        }

        Dataset& start_transaction() {
            m_dataset->StartTransaction();
            return *this;
        }

        Dataset& commit_transaction() {
            m_dataset->CommitTransaction();
            m_edit_count = 0;
            return *this;
        }

        void prepare_edit() {
            if (m_max_edit_count != 0 && m_edit_count == 0) {
                start_transaction();
            }
        }

        void finalize_edit() {
            if (m_max_edit_count != 0 && ++m_edit_count > m_max_edit_count) {
                commit_transaction();
            }
        }

        Dataset& enable_auto_transactions(uint64_t edits = 100000) noexcept {
            m_max_edit_count = edits;
            return *this;
        }

        Dataset& disable_auto_transactions() {
            if (m_max_edit_count != 0 && m_edit_count > 0) {
                commit_transaction();
            }
            m_max_edit_count = 0;
            return *this;
        }

    }; // class Dataset

    class _GISExport Layer {

        detail::Options m_options;
        Dataset& m_dataset;
        OGRLayer* m_layer;

    public:

        Layer(Dataset& dataset, const String& layer_name, OGRwkbGeometryType type, const std::vector<String>& options = {}) :
            m_options(options),
            m_dataset(dataset),
            m_layer(dataset.get().CreateLayer(layer_name.c_str(), &dataset.srs().get(), type, m_options.get())) {
            if (!m_layer) {
                throw gdal_error{String{"failed to create layer '"} + layer_name + "'",
                                 OGRERR_NONE,
                                 dataset.driver_name(),
                                 dataset.dataset_name(),
                                 layer_name};
            }
        }

        OGRLayer& get() noexcept {
            return *m_layer;
        }

        const OGRLayer& get() const noexcept {
            return *m_layer;
        }

        Dataset& dataset() const noexcept {
            return m_dataset;
        }

        const char* name() const {
            return m_layer->GetName();
        }

        Layer& add_field(const String& field_name, OGRFieldType type, int width, int precision=0) {
            OGRFieldDefn field(field_name.c_str(), type);
            field.SetWidth(width);
            field.SetPrecision(precision);

            if (m_layer->CreateField(&field) != OGRERR_NONE) {
                throw gdal_error{String{"failed to create field '"} + field_name + "' in layer '" + name() + "'",
                                 OGRERR_NONE,
                                 m_dataset.driver_name(),
                                 m_dataset.dataset_name(),
                                 name(),
                                 field_name};
            }

            return *this;
        }

        void create_feature(OGRFeature* feature) {
            dataset().prepare_edit();
            const auto result = m_layer->CreateFeature(feature);
            if (result != OGRERR_NONE) {
                throw gdal_error{String{"creating feature in layer '"} + name() + "' failed",
                                 result,
                                 dataset().driver_name(),
                                 dataset().dataset_name()};
            }
            dataset().finalize_edit();
        }

        Layer& start_transaction() {
            return *this;
        }

        Layer& commit_transaction() {
            return *this;
         }

    }; // class Layer

    struct ogr_geometry_deleter {
        void operator()(OGRGeometry* geometry) {
            OGR_G_DestroyGeometry(geometry);
        }

    }; // struct ogr_geometry_deleter

    using point_type = std::unique_ptr<OGRPoint, ogr_geometry_deleter>;
    using linestring_type = std::unique_ptr<OGRLineString, ogr_geometry_deleter>;
    using polygon_type = std::unique_ptr<OGRPolygon, ogr_geometry_deleter>;
    using multipolygon_type = std::unique_ptr<OGRMultiPolygon, ogr_geometry_deleter>;
    using ring_type = std::unique_ptr<OGRLinearRing, ogr_geometry_deleter>;

    class _GISExport Feature {

        struct ogr_feature_deleter {

            void operator()(OGRFeature* feature) {
                 OGRFeature::DestroyFeature(feature);
            }

        }; // struct ogr_feature_deleter

        Layer& m_layer;
        std::unique_ptr<OGRFeature, ogr_feature_deleter> m_feature;

    public:

        Feature(Layer& layer, std::unique_ptr<OGRGeometry, ogr_geometry_deleter>&& geometry) :
            m_layer(layer),
            m_feature(OGRFeature::CreateFeature(m_layer.get().GetLayerDefn())) {
            if (!m_feature) {
                throw std::bad_alloc{};
            }
            const auto result = m_feature->SetGeometryDirectly(geometry.release());
            if (result != OGRERR_NONE) {
                throw gdal_error{String{"setting feature geometry in layer '"} + m_layer.name() + "' failed",
                                 result,
                                 m_layer.dataset().driver_name(),
                                 m_layer.dataset().dataset_name()};
            }
        }

        void add_to_layer() {
            m_layer.create_feature(m_feature.get());
        }

        template <typename T>
        Feature& set_field(int n, T&& arg) {
            m_feature->SetField(n, std::forward<T>(arg));
            return *this;
        }

        template <typename T>
        Feature& set_field(const char* name, T&& arg);

    }; // class Feature

    template <typename T>
    Feature& Feature::set_field(const char* name, T&& arg) {
        m_feature->SetField(name, std::forward<T>(arg));
        return *this;
    }

    class _GISExport Geometry {
        struct ogr_geometry_deleter {
            void operator()(OGRGeometry* geometry) {
                OGRGeometryFactory::destroyGeometry(geometry);
            }
        }; // struct ogr_feature_deleter

    public:
        Geometry(OGRGeometry* geometry)
        {
            m_geometry.reset(geometry);
        }

        static Geometry createFromWkb(const String& hexWkb)
        {
            StringStream ss;
            char buffer[2];
            for (size_t i = 0; i < hexWkb.length(); i += 2) {
                buffer[0] = hexWkb[i];
                buffer[1] = hexWkb[i + 1];
                ss << static_cast<unsigned char>(std::stoi(buffer, nullptr, 16));
            }

            OGRGeometry* geometry = nullptr;
            auto err = OGRGeometryFactory::createFromWkb(ss.str().data(), nullptr, &geometry);
            if (geometry != nullptr) {
                return Geometry(geometry);
            }

            throw gdal_error{ "createFromWkb failed", err };
        }

        String exportToWkt()
        {
            String result;
            char* wkt = nullptr;
            OGRErr err = m_geometry->exportToWkt(&wkt);
            if (wkt != nullptr && err == OGRERR_NONE) {

                result = wkt;
                CPLFree(wkt);
            }
            return result;
        }

        OGRGeometry* geom() 
        {
            return m_geometry.get();
        }

        OGRwkbGeometryType type()
        {
            return m_geometry->getGeometryType();
        }

        String typeName()
        {
            OGRwkbGeometryType geometryType = type();
            return OGRGeometryTypeToName(geometryType);
        }

        std::unique_ptr<OGRGeometry, ogr_geometry_deleter> m_geometry;
    };
} // namespace gdalcpp

#endif // GDALCPP_HPP
